package com.java110.mall.openapi.bmo.impl;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.dto.communityRecommend.CommunityRecommendDto;
import com.java110.intf.market.ICommunityRecommendV1InnerServiceSMO;
import com.java110.mall.openapi.bmo.IMallCommonApiBmo;
import com.java110.utils.cache.CommonCache;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.ListUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("queryCommunityRecommendBmoImpl")
public class QueryCommunityRecommendBmoImpl implements IMallCommonApiBmo {

    @Autowired
    private ICommunityRecommendV1InnerServiceSMO communityRecommendV1InnerServiceSMOImpl;

    @Override
    public void validate(ICmdDataFlowContext context, JSONObject reqJson) {
        Assert.hasKeyAndValue(reqJson, "communityId", "未包含小区");
        Assert.jsonObjectHaveKey(reqJson, "page", "请求中未包含page信息");
        Assert.jsonObjectHaveKey(reqJson, "row", "请求中未包含row信息");
    }

    @Override
    public void doCmd(ICmdDataFlowContext context, JSONObject reqJson) {
        CommunityRecommendDto communityRecommendDto = BeanConvertUtil.covertBean(reqJson, CommunityRecommendDto.class);

        int count = communityRecommendV1InnerServiceSMOImpl.queryCommunityRecommendsCount(communityRecommendDto);

        List<CommunityRecommendDto> communityRecommendDtos = null;

        if (count > 0) {
            communityRecommendDtos = communityRecommendV1InnerServiceSMOImpl.queryCommunityRecommends(communityRecommendDto);
        } else {
            communityRecommendDtos = new ArrayList<>();
        }

        freshMappAppUrl(communityRecommendDtos);

        ResultVo resultVo = new ResultVo((int) Math.ceil((double) count / (double) reqJson.getInteger("row")), count, communityRecommendDtos);

        ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK);

        context.setResponseEntity(responseEntity);
    }

    private void freshMappAppUrl(List<CommunityRecommendDto> communityRecommendDtos) {
        if (ListUtil.isNull(communityRecommendDtos)) {
            return;
        }

        String mallUrl = MappingCache.getValue(MappingConstant.URL_DOMAIN, "MALL_URL");
        for (CommunityRecommendDto communityRecommendDto : communityRecommendDtos) {
            communityRecommendDto.setMallAppUrl(mallUrl);
        }
    }
}
